package chenji.yourticket;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.inventory.ItemStack;

import chenji.yourticket.inventory.InventoryManager.OpeningInventoryType;

@SuppressWarnings("deprecation")
public class YListener implements Listener {

	@EventHandler
	public void onClick(InventoryClickEvent e) {
		Player p = (Player) e.getWhoClicked();
		if (Main.getInventoryManager().isOpening(p)) {
			e.setCancelled(true);
		} else {
			return;
		}
		if (e.getClickedInventory() == null) {
			return;
		}
		OpeningInventoryType i = Main.getInventoryManager().getOpeningInventoryType(p);
		if (i == null) {
			return;
		}
		if (i.equals(OpeningInventoryType.EditorManager)) {
			Main.getEditorManager().clickInventory(p, e.getSlot(), e.getClickedInventory());
			return;

		}
		if (i.equals(OpeningInventoryType.ModelManager)) {
			Main.getModelManager().clickInventory(p, e.getSlot(), e.getAction());
			return;
		}
		if (i.equals(OpeningInventoryType.PressManager)) {
			Main.getPressManager().clickInventory(e.getSlot(), p);
			return;
		}
	}

	@EventHandler
	public void onClose(InventoryCloseEvent e) {
		Player p = (Player) e.getPlayer();
		if (Main.getInventoryManager().isOpening(p)) {
			Main.getModelManager().closeInventory(p);
			Main.getEditorManager().closeInventory(p);
		}
		Main.getInventoryManager().closeInventory(p);
	}

	@EventHandler
	public void onPlayerChat(PlayerChatEvent e) {
		e.setCancelled(Main.getEditorManager().chatListener(e.getPlayer(), e.getMessage()));
	}

	@EventHandler
	public void PreventCraft(InventoryClickEvent e) {
		if (e.getClickedInventory() == null) {
			return;
		}
		String verify = Main.getConfiguration().getanti_counterfeiting().split("%player%")[0].replaceAll("&", "§");
		int i = 0;
		int max;
		if (e.getInventory().getType().equals(InventoryType.CRAFTING)) {
			max = 4;
		} else if (e.getInventory().getType().equals(InventoryType.WORKBENCH)) {
			max = 9;
		} else {
			return;
		}
		while (i<max) {
			i++;
			ItemStack item = e.getInventory().getItem(i);
			if (item == null) {
				continue;
			}
			if (item.getItemMeta() == null) {
				continue;
			}
			if (!(item.getItemMeta().hasLore())) {
				continue;
			}
			String lastLine = item.getItemMeta().getLore().get(item.getItemMeta().getLore().size() - 1);
			if (lastLine.contains(verify)) {
				e.getWhoClicked().closeInventory();
			}
		
		}

	}
}
